const express = require('express');
const router = express.Router();
const {User} = require('../../models');
const {Op} = require('sequelize');
const {BadRequestError,UnauthorizedError,NotFoundError} = require('../../utils/errors');
const {Success,failure} = require('../../utils/responses');
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken');


router.post('/sing_in', async (req, res) => {
    try{
        //获得用户输入的账号密码
        const{login,password} = req.body;
        //用户名/邮箱和密码不能为空
        if(!login){
            throw new BadRequestError('用户名/邮箱必须填写');
        }
        if(!password){
            throw new BadRequestError('密码必须填写');
        }
        //使用邮箱或者使用用户名登录都可以
        const condition = {
            where:{
                [Op.or]:[
                    {email:login},
                    {username:login},
                ]
            }
        };
        //查询是否有这个用户名/邮箱
        const user = await User.findOne(condition);
        if(!user){
            throw new NotFoundError('用户名不存在，无法登录');
        }
        //密码验证
        const isPasswordValid = bcrypt.compareSync(password, user.password);
        if(!isPasswordValid){
            throw new UnauthorizedError('密码错误');
        }
        //权限验证
        if(user.role!==100){
            throw new UnauthorizedError('非管理员用户无法登录');
        }
        const token = jwt.sign({
            userId: user.id
        },process.env.SECRET,{expiresIn: '30d'});
        Success(res,"登录成功",{token});
    }catch(error){
        failure(res,error);
    }
});

module.exports = router;